const winConfig = window._CONFIG || {}
const {
    urlRandom,
    tampering,
    SM4Rncrypt,
    timeout
} = winConfig

export const requestTimeOut = timeout

/**
 * 防重放，这里添加时间戳和6位随机数
 * @param {*} config
 */
export const replayDefence = (config) => {
    if (urlRandom && config.url) {
        const nonce = Math.floor(Math.random() * 1000000)
        config.params = {
            _t: Date.parse(new Date()),
            nonce,
            ...config.params
        }
    }
}

/**
 * 报文加密，这里使用base64代替加密，你可以替换成SM4加密
 * @param {*} config
 */
export const encryptRequest = (config) => {
    if (SM4Rncrypt && config.url && config.data) {
        if (['post', 'put', 'delete'].includes(config.method)) {
            config.headers["Content-Type"] = "application/json";
            let jsonStr = JSON.stringify(config.data);
            config.data = btoa(jsonStr);
        }
    }
}

/**
 * 防篡改，这里是btoa(url+params+btoa(data))，你可以再加盐
 * @param {*} config
 */
export const distortDefence = (config) => {
    if (tampering && config.url) {
        let validCode = `${config.url}`
        if (config.params) {
            for (let key in config.params) {
                validCode += `&${key}=${config.params[key]}`
            }
        }
        if (config.data && config.method != 'get') {
            validCode += SM4Rncrypt ? config.data : JSON.stringify(config.data);
        }
        console.log('validCode:', validCode)
        config.headers["sign"] = btoa(validCode)
    }
}


/**
 * 加载loading
 */
export const loading = () => {
    const loadingFixedDiv = document.getElementById("loading-fixed");
    if(!loadingFixedDiv){
        let loadingFixed = document.createElement("div");
        loadingFixed.className = "loading-fixed";
        loadingFixed.id = "loading-fixed";
        let loading = document.createElement("div");
        loading.className = "loading";
        let img = document.createElement("img");
        img.src = require("../assets/img/loading.gif")
        loading.appendChild(img)
        loadingFixed.appendChild(loading)
        document.body.appendChild(loadingFixed);
    }
}

/**
 * 删除loading
 */
export const removeLoading = () => {
    document.getElementById("loading-fixed")?.remove()
}
